import { useRef, useEffect } from 'react'
import {
  InputGroup,
  InputGroupInput,
  InputGroupAddon,
} from '@/components/ui/input-group'
import { Button } from '@/components/ui/button'
import { SearchIcon } from 'lucide-react'

type Props = {
  onSearch: (keywords: string) => void
  children?: React.ReactNode
}

const SearchBar = ({ onSearch, children }: Props): JSX.Element => {

  const keywordsRef = useRef<string>(localStorage.getItem('cacheSearchKeywords') || '')

  useEffect(() => {
    console.info('[render Component]:%c SearchBar', 'color: red;', Date.now())
  })

  const handleKeywordsChange = (e: { target: { value: string } }): void => {
    keywordsRef.current = e.target.value
  }

  const onKeyUp = (e: { key: string, keyCode: number }): void => {
    if (e.key === 'Enter' || e.keyCode === 13) {
      onSearch(keywordsRef.current)
    }
  }

  return <div className='search-bar'>
    <InputGroup>
      <InputGroupInput placeholder={keywordsRef.current ? ('上次搜索 ' + keywordsRef.current) : '搜索 歌手 / 歌曲 / 专辑'} onChange={handleKeywordsChange} onKeyUp={onKeyUp} />
      <InputGroupAddon>
        <SearchIcon />
      </InputGroupAddon>
    </InputGroup>
    <Button className='shadow' onClick={() => onSearch(keywordsRef.current)}>搜索</Button>
    {children}
  </div>
}

export default SearchBar
